package com.honglang.module.user.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import com.honglang.module.user.entity.User;
import com.honglang.module.user.service.UserService;
import com.honglang.struts2.action.BaseAction;
import com.opensymphony.xwork2.Action;

public class RegisterAction extends BaseAction{
	private User user;
	private UserService userService;
	
	





	
	public String register(){
		if(user.getUserName() == null || user.getUserName().isEmpty()){
			return Action.INPUT;
		}
		user.setRegisterDate(new Date());
		userService.saveUser(user);
		return Action.SUCCESS;
	}

	
	/**
	 * check the userName if it is exist.
	 * @return
	 * @throws IOException 
	 */
	public String checkUserName() throws IOException{
		
		String userName = this.getRequest().getParameter("validateValue");
	    this.returnJSON(!userService.isUserNameExist(userName));	
		return Action.NONE ;
	}
	
	
	/**
	 * validate veriCode;
	 * @return
	 * @throws IOException
	 */
	public String checkVeriCode() throws IOException{
		
		String var = this.getRequest().getParameter("validateValue");
		String veriCode = (String)this.getSession().getAttribute("CheckCode");
		this.returnJSON(veriCode.equalsIgnoreCase(var));
		return Action.NONE;
		
	}
	
	
	public String checkEmailExist() throws IOException {
		
		String email = this.getRequest().getParameter("validateValue");
	    this.returnJSON(!userService.isEmailExist(email));	
		return Action.NONE ;
	}
	
	
	/**
	 * wrap the validate result in JSON format
	 * @param bool
	 * @throws IOException
	 */
	protected void returnJSON(boolean bool) throws IOException{
		String validateError = this.getRequest().getParameter("validateError");
	    String validateId = this.getRequest().getParameter("validateId");
		List<String> list = new ArrayList<String>();
		list.add(validateId);
		list.add(validateError);
		list.add(String.valueOf(bool));	
		Map<String,List<String>> map = new HashMap<String,List<String>>();
		map.put("jsonValidateReturn", list);
		JSONObject json = JSONObject.fromObject(map);
		this.getResponse().getWriter().write(json.toString());
		
	}
	
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}


	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
}